﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using mmoss.orm;
using mmoss.application.classes;
using mmoss.classes;
using mmoss.classes.Interfaces;
using mmoss.configuration;

namespace mmoss.application
{
    public partial class frmSale : Form
    {

        public Cart CurrentCart { get; set; }
        //private posCart _currentCart;
        private Patient _currentPatient;
        public PatientCheckIn CurrentCheckin { get; set; }
        public frmSale()
        {
            InitializeComponent();
            this.Load += new EventHandler(frmSale_Load);
        }
        public frmSale(Patient l_patient)
        {
            InitializeComponent();
            this.Load += new EventHandler(frmSale_Load);
            dgCart.AutoGenerateColumns = false;
            dgTaxes.AutoGenerateColumns = false;

            loadInfo(l_patient);
            loadCart();
        }
        void frmSale_Load(object sender, EventArgs e)
        {
            txtDiscountCode.Enter += new EventHandler(txtDiscountCode_Enter);
            txtDiscountPerc.Enter += delegate(object ss,EventArgs ee)
            {
                ((TextBox)ss).SelectAll();
            };
            txtDiscountDollar.Enter += delegate(object ss,EventArgs ee)
            {
                ((TextBox)ss).SelectAll();
            };
            txtCartTotal.Enter += delegate(object ss,EventArgs ee)
            {
                ((TextBox)ss).SelectAll();
            };
            txtSubTotal.Enabled=false;
            txtDiscountDollar.Leave += new EventHandler(txtDiscountDollar_Leave);
            txtDiscountCode.Leave += new EventHandler(txtDiscountCode_Leave);
            txtDiscountPerc.Leave += new EventHandler(txtDiscountPerc_Leave);
            txtCartTotal.Leave += new EventHandler(txtCartTotal_Leave);
            //mmossEvents.PatientCheckIn += new mmossEvents.checkinPatient(mmossEvents_PatientCheckIn);
            //update cart event
            dgCart.CellValueChanged += new DataGridViewCellEventHandler(dgCart_CellValueChanged);
        }

        void dgCart_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            loadCart();            
        }

        void txtDiscountCode_Enter(object sender, EventArgs e)
        {
            //show keyboard
            //Keyboardcontrol l_keyboard = new Keyboardcontrol();
            //l_keyboard.Show();
            if (Default.TouchScreen)
            {
                frmTouchKeyboard l_keyboard = new frmTouchKeyboard();
                l_keyboard.MdiParent = this.MdiParent;
                l_keyboard.WindowState = FormWindowState.Maximized;
                l_keyboard.Show();
                l_keyboard.FormClosed += new FormClosedEventHandler(delegate(object s, FormClosedEventArgs ev)
                {
                    ((TextBox)sender).Text = ((frmTouchKeyboard)s).TypedString;
                }
                );
            }
        }



        void txtCartTotal_Leave(object sender, EventArgs e)
        {
            //recalc discounts based on previous cart and new cart
            decimal dOut;
            if (!decimal.TryParse(txtCartTotal.Text, out dOut))
            {
                MessageBox.Show("Must be numeric value");
                txtCartTotal.Text = "";
                txtCartTotal.Focus();
                return;
            }
            decimal dSubTotal = Math.Round((dOut/(decimal.Parse("1")+ CurrentCart.CartTaxs.Sum(p=>p.LocationTax.mmcTaxRate))), 2);
            decimal dDiscount = Math.Round(CurrentCart.cartSubTotal - dSubTotal, 2);
            decimal dDiscountPerc = Math.Round((1 - dSubTotal / CurrentCart.cartSubTotal)*100, 2);
            //update db
            CurrentCart.cartDiscountDollar = dDiscount;
            CurrentCart.cartDiscountPerc = dDiscountPerc;
            txtDiscountDollar.Text = dDiscount.ToString();
            txtDiscountPerc.Text = dDiscountPerc.ToString();
            //txtDiscountDollar_Leave(sender, e);
            loadCart();
        }

        void txtDiscountPerc_Leave(object sender, EventArgs e)
        {
            decimal dOut;
            if (((TextBox)sender).Text.Trim() == "") return;
            if (!decimal.TryParse(txtDiscountPerc.Text, out dOut))
            {
                MessageBox.Show("Must be numeric value");
                txtDiscountPerc.Text = "";
                txtDiscountPerc.Focus();
                return;
            }
            decimal dDiscountDollar = Math.Round(CurrentCart.cartSubTotal* dOut*decimal.Parse(".01"), 2);
            txtDiscountDollar.Text = dDiscountDollar.ToString();
            CurrentCart.cartDiscountDollar = dDiscountDollar;
            CurrentCart.cartDiscountPerc = dOut;
            //dbConn.db.SubmitChanges();
            loadCart();
        }

        void txtDiscountDollar_Leave(object sender, EventArgs e)
        {
            decimal dOut;
            if (((TextBox)sender).Text.Trim() == "") return;
            if (!decimal.TryParse(txtDiscountDollar.Text, out dOut))
            {
                MessageBox.Show("Must be numeric value");
                txtDiscountDollar.Text = "";
                txtDiscountDollar.Focus();
                return;
            }
            decimal dDiscountPerc = Math.Round((dOut / CurrentCart.cartSubTotal )*100, 2);
            txtDiscountPerc.Text = dDiscountPerc.ToString();
            CurrentCart.cartDiscountDollar = dOut;
            CurrentCart.cartDiscountPerc = dDiscountPerc;
            //dbConn.db.SubmitChanges();
            loadCart();
        }

        void txtDiscountCode_Leave(object sender, EventArgs e)
        {
            CurrentCart.promoCode = ((TextBox)sender).Text.Trim().ToLower();
            loadCart();
        }

        private void loadInfo(Patient l_patient)
        {
            //set the label for this patient
            lblPatientInfo.Text = "Patient: " + l_patient.patientLastName + ", " + l_patient.patientFirstName;
            _currentPatient = l_patient;

            //get cart if one exists
            if (dbConn.db.Carts.GetOpenCartByPatientID(_currentPatient.patientID).Count > 0)
            {
                CurrentCart = dbConn.db.Carts.GetOpenCartByPatientID(_currentPatient.patientID).First();
            }
            else
            {
                CurrentCart = new Cart();
                CurrentCart.Patient = _currentPatient;
                CurrentCart.Location = Default.CurrentLocation;
                CurrentCart.User = Default.CurrentUser;
                //dbConn.db.Carts.InsertOnSubmit(CurrentCart);
                //dbConn.db.SubmitChanges();
                foreach (LocationTax l_taxItem in Default.CurrentLocation.LocationTaxs)
                {
                    CartTax l_tax = new CartTax();
                    l_tax.LocationTax = l_taxItem;
                    l_tax.Cart = CurrentCart;
                    
                }
                dbConn.db.SubmitChanges();
            }
        }
        void mmossEvents_PatientCheckIn(Patient l_patient)
        {
            //new patient checked in from patient screen, refresh
            //dgPatientsWaiting.DataSource = Default.LoggedInPatients;
        }

        private void btnMeds_Click(object sender, EventArgs e)
        {
            frmSubMenu l_win = new frmSubMenu(dbConn.db.InventoryItemTypes.Single(p=>p.InventoryTypeID==1));
            l_win.MdiParent = this.MdiParent;
            l_win.Show();
            l_win.FormClosed += new FormClosedEventHandler(l_win_FormClosed);
        }
        private void loadCart()
        {
            if (CurrentCart.CartItems.Count>0)
            {
                //recalculat cart
                CurrentCart.calcCart();

                //bind
                dgCart.DataSource = CurrentCart.CartItems;
                dgTaxes.DataSource = CurrentCart.CartTaxs;
                txtSubTotal.Text = (CurrentCart.cartSubTotal-(CurrentCart.cartDiscountDollar.HasValue?CurrentCart.cartDiscountDollar.Value:0)).ToString();
                txtCartTotal.Text = CurrentCart.cartTotal.ToString();
                txtDiscountDollar.Text = CurrentCart.cartDiscountDollar.ToString();
                txtDiscountPerc.Text = CurrentCart.cartDiscountPerc.ToString();
            }
        }

        void l_win_FormClosed(object sender, FormClosedEventArgs e)
        {
            //*** add new item to cart ***//
            if (((frmSubMenu)sender).ChosenItem != null)
            {
                CurrentCart.CartItems.Add(((frmSubMenu)sender).ChosenCartItem);
                dbConn.db.SubmitChanges();

                //load the cart
                loadCart();
            }
            //fire event for wcf listening
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CardProcess l_card = new CardProcess();
            l_card.CurrentCart = CurrentCart;
            l_card.CurrentPatient = _currentPatient;
            l_card.MdiParent = this.MdiParent;
            l_card.Show();
            l_card.FormClosed += new FormClosedEventHandler(l_card_FormClosed);
        }

        void l_card_FormClosed(object sender, FormClosedEventArgs e)
        {
            string sTransactionID = ((CardProcess)sender).transactionID;
            //handle cart credit card transaction return
            //todo - put in 
            IEComm l_return = ((CardProcess)sender).CurrentEComm;
            //todo - pull back from window
            //checkout cart
            if (sTransactionID != "")
            {
                CurrentCart.transactionID = sTransactionID;
                CurrentCart.ccPayment = CurrentCart.cartTotal;
                CurrentCart.cartCheckoutDate = DateTime.Now;
                //checkout patient
                CurrentCheckin.checkOutPost = DateTime.Now;
                //update db
                dbConn.db.SubmitChanges();
                MessageBox.Show("Patient Checked Out Successfully");
                //update docked patient list
                ((frmContainer)this.MdiParent).updatePatientList();
                //close window
                this.Close();
            }
        }

        private void btnOrderHistory_Click(object sender, EventArgs e)
        {

        }

        private void btnCash_Click(object sender, EventArgs e)
        {
            CashRegister l_register = new CashRegister(CurrentCart.cartTotal);
            l_register.MdiParent = this.MdiParent;
            l_register.FormClosed += new FormClosedEventHandler(l_register_FormClosed);
            l_register.Show();
        }

        void l_register_FormClosed(object sender, FormClosedEventArgs e)
        {
            //cash register closed.  
            //if total was tendered, close out sale and print receipt
            if (((CashRegister)sender).CashTendered>0)
            {
                //l_cart.transactionID = sTransactionID;
                CurrentCart.cashPayment = CurrentCart.cartTotal;
                CurrentCart.cartTotal = CurrentCart.cartTotal;
                CurrentCart.cartCheckoutDate = DateTime.Now;

                //checkout patient
                CurrentCheckin.checkOutPost = DateTime.Now;
                //update db
                dbConn.db.SubmitChanges();
                MessageBox.Show("Patient Checked Out Successfully");
                //update docked patient list
                ((frmContainer)this.MdiParent).updatePatientList();
                //close window
                this.Close();
            }

        }

        private void btnJoints_Click(object sender, EventArgs e)
        {
            frmSubMenu l_win = new frmSubMenu(dbConn.db.InventoryItemTypes.Single(p => p.InventoryTypeID == 9));
            l_win.MdiParent = this.MdiParent;
            l_win.Show();
            l_win.FormClosed += new FormClosedEventHandler(l_win_FormClosed);
        }

        private void btnNoPurchase_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to checkout with no purchase?", "confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                CurrentCheckin.checkOutPost = DateTime.Now;
                dbConn.db.SubmitChanges();
                this.Close();
            }
        }

        private void btnHash_Click(object sender, EventArgs e)
        {
            frmSubMenu l_win = new frmSubMenu(dbConn.db.InventoryItemTypes.Single(p => p.InventoryTypeID == 5));
            l_win.MdiParent = this.MdiParent;
            l_win.Show();
            l_win.FormClosed += new FormClosedEventHandler(l_win_FormClosed);

        }

        private void btnEdible_Click(object sender, EventArgs e)
        {
            frmSubMenu l_win = new frmSubMenu(dbConn.db.InventoryItemTypes.Single(p => p.InventoryTypeID == 2));
            l_win.MdiParent = this.MdiParent;
            l_win.Show();
            l_win.FormClosed += new FormClosedEventHandler(l_win_FormClosed);

        }

    }
}
